package com.wang.service.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSONObject;
import com.wang.common.pojo.InfoEnum;
import com.wang.common.service.BaseService;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.util.PageInfoUtil;
import com.wang.pojo.AEmail;
import com.wang.pojo.AEmailEnum;
import com.wang.pojo.AResult;
import com.wang.pojo.AResultEnum;
import com.wang.pojo.ASensitiveWords;
import com.wang.pojo.ASensitiveWordsEnum;
import com.wang.service.IEmailDbService;
import com.wang.service.IEmailOperService;

/**
 * 邮箱模块Service的实现类
 * 
 * @author YH
 *
 */
public class EmailOperServiceImpl extends BaseService implements IEmailOperService {
	private IEmailDbService emailDbService = new EmailDbServiceImpl();
	
	public EmailOperServiceImpl() {
		this.reloadSensitive();
	}

	@Override
	public JSONObject saveBatchEmailService(InputStream is) {
		JSONObject resultJSON = new JSONObject();
		
		int totalCount = 0 ;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String line = "" ; 
			int count = 1 ; 
			
			List<AEmail> emailsList = new ArrayList<AEmail>();
			while( (line = br.readLine()) != null) {
				totalCount ++ ;
				
				try {
					line = line.trim() ; 
					
					AEmail email = new AEmail();
					email = email.parse(line);
					
					if(email != null) {
						emailsList.add(email);
					}else
					{
						System.out.println(count + "==解析失败==" + line);
					}
					if(count % ConstatFinalUtil.BATCH_SIZE == 0 ) {
						/* 批量保存 */
						this.emailDbService.saveBatchEmailService(emailsList);
						emailsList = new ArrayList<AEmail>();
						//break ; 
						System.out.println(count + "==执行条数==");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				count ++ ; 
			}
			
			/* 批量保存 */
			this.emailDbService.saveBatchEmailService(emailsList);
			resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_TOTAL.getInfo(), totalCount);
			resultJSON.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		} catch (Exception e) {
			e.printStackTrace();
			resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJSON ; 
	}

	@Override
	public JSONObject verifyBatchEmailService(List<AEmail> emailList) {
		JSONObject resultJSON = new JSONObject();
		
		for (AEmail emailTemp : emailList) {
			this.verifyOneEmailService(emailTemp);
		}
		
		resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
		resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
		return resultJSON;
	}

	/**
	 * 敏感词:对sender,rcpt超作用
	 * 白名单对fromname起作用
	 * url:对url超作用
	 */
	/**
	 *
	 */
	@Override
	public JSONObject verifyOneEmailService(AEmail email) {
		JSONObject resultJSON = new JSONObject();
		if("true".equalsIgnoreCase(email.getAuthuser())) {
			/* 说明已经查询到数据 */
			resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			return resultJSON ; 
		}
		/* 查询一下结果表中是否有数据,如果有数据说明已经检验过了 */
		Map<String,Object> condMap = new HashMap<String, Object>();
		/* 根据邮箱的id查询 */
		condMap.put("emailId", email.getId());
		AResult resultData = this.emailDbService.findOneResultService(condMap);
		if(resultData != null) {
			/* 说明已经查询到数据 */
			resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_RECORD_EXISTS.getCode());
			resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_RECORD_EXISTS.getCode())));
			return resultJSON ; 
		}
		
		/* 判断是否包含敏感词 */
		resultData = new AResult();
		resultData.setEmailId(email.getId());
		resultData.setRcpt(email.getRcpt());
		resultData.setSender(email.getSender());
		resultData.setUrl(email.getUrl());
		resultData.setFromname(email.getFromname());
		/*
		 * 黑名单
		 *  #### 邮箱地址（sender, rcpt）：
			[salt+hash]@[salt+hash替换掉敏感域名，其它保留].[真实TLD]
			#### 示例：
		 * */
		for (Entry<String, ASensitiveWords> entryTemp : ConstatFinalUtil.HMD_SENSTIVE_MAP.entrySet()) {
			String key = entryTemp.getKey() ; 
			ASensitiveWords sensitiveWords = entryTemp.getValue() ; 
			/* hash操作 */
			String keyEncode = DigestUtils.md5Hex(key).substring(0,16);
			if(resultData.getFromname().contains(key)) {
				String fromname = resultData.getFromname().replaceAll(key, "[" + key + "]") ;
				resultData.setFromname(fromname);
				/* 存储状态 */
				resultData.setWhiteStatus(AResultEnum.WHITESTATUS_ENABLED.getCode());
			}
			
			if(resultData.getSender().contains(key)) {
				String sender = resultData.getSender().replaceAll(key, "[" + key + "]") ;
				resultData.setSender(sender);
				/* 存储状态 */
				resultData.setWhiteStatus(AResultEnum.WHITESTATUS_ENABLED.getCode());
			}
		}
		
		/*
		 * url
		 *  #### 邮箱地址（sender, rcpt）：
			[salt+hash]@[salt+hash替换掉敏感域名，其它保留].[真实TLD]
			#### 示例：
		 * */
		for (Entry<String, ASensitiveWords> entryTemp : ConstatFinalUtil.URL_SENSTIVE_MAP.entrySet()) {
			String key = entryTemp.getKey() ; 
			ASensitiveWords sensitiveWords = entryTemp.getValue() ; 
			/* hash操作 */
			if(resultData.getUrl().contains(key)) {
				String url = resultData.getUrl().replaceAll(key, "[" + key + "]") ;
				resultData.setUrl(url);
				/* 存储状态 */
				resultData.setUrlStatus(AResultEnum.URLSTATUS_ENABLED.getCode());
			}
		}
		
		/* 是否群发 */
		String rcpt = resultData.getRcpt();
		String emailIndex = "@" ;
		int emailCount = 0 ; 
		while(rcpt.indexOf(emailIndex) != -1)
		{
			rcpt = rcpt.substring(rcpt.indexOf(emailIndex) + 1, rcpt.length());
			emailCount ++ ; 
		}
		if(emailCount >= 2 ) {
			/* 群发 */
			resultData.setGroupStatus(AResultEnum.GROUPSTATUS_YES.getCode());
		}
		
		byte level = Integer.valueOf(resultData.getUrlStatus() + resultData.getAnonStatus() + resultData.getWhiteStatus() + resultData.getGroupStatus()).byteValue(); 
		resultData.setLevel(level);
		
		if(resultData.getLevel() > 0 ) {
			resultJSON = this.emailDbService.saveOneResultService(resultData);
		}else
		{
			email.setStatus(AEmailEnum.STATUS_PATCHED.getCode());
			emailDbService.updateOneEmailService(email);
			resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
		}
		return resultJSON;
	}

	@Override
	public JSONObject reloadSensitive() {
		Map<String,Object> condMap = new HashMap<String, Object>();
		JSONObject resultJSON = new JSONObject();
		/* 查询黑名单 */
		condMap.clear();
		condMap.put("swType", ASensitiveWordsEnum.SWTYPE_HMD.getCode());
		condMap.put("status", ASensitiveWordsEnum.STATUS_ENABLED.getCode());
		List<ASensitiveWords> hmdList = this.emailDbService.findCondListSensitiveWordsService(null, condMap);
		/* 清空敏感词 */
		ConstatFinalUtil.HMD_SENSTIVE_MAP.clear();
		for (ASensitiveWords sensitiveWordsTemp : hmdList) {
			ConstatFinalUtil.HMD_SENSTIVE_MAP.put(sensitiveWordsTemp.getName(), sensitiveWordsTemp);
		}
		System.out.println("==加载白名单数量==" + hmdList.size());
		
		/* 查询url */
		condMap.clear();
		condMap.put("swType", ASensitiveWordsEnum.SWTYPE_URL.getCode());
		condMap.put("status", ASensitiveWordsEnum.STATUS_ENABLED.getCode());
		List<ASensitiveWords> urlList = this.emailDbService.findCondListSensitiveWordsService(null, condMap);
		/* 清空敏感词 */
		ConstatFinalUtil.URL_SENSTIVE_MAP.clear();
		for (ASensitiveWords sensitiveWordsTemp : urlList) {
			ConstatFinalUtil.URL_SENSTIVE_MAP.put(sensitiveWordsTemp.getName(), sensitiveWordsTemp);
		}
		System.out.println("==加载url数量==" + urlList.size());
		
		JSONObject dataJson = new JSONObject();
		dataJson.put("hmdNum", hmdList.size());
		dataJson.put("urlNum", urlList.size());
		resultJSON.put("data", dataJson);
		
		
		resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
		resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
		return resultJSON ; 
	}

	@Override
	public JSONObject verifyBatchEmailService() {
		JSONObject resultJSON = new JSONObject();
		/* 设置分页信息 */
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		pageInfoUtil.setPageSize(ConstatFinalUtil.BATCH_SIZE);
		Map<String,Object> condMap = new HashMap<String, Object>();
		condMap.put("status", AEmailEnum.STATUS_UNPATCH.getCode());
		/* 获取页条数 */
		this.emailDbService.findCondListEmailService(pageInfoUtil, condMap);
		for(int i = 1 ; i <= pageInfoUtil.getTotalPage() ; i ++) {
			pageInfoUtil.setCurrentPage(i);
			/* 查询数据 */
			List<AEmail> emailList = this.emailDbService.findCondListEmailService(pageInfoUtil, condMap);
			this.verifyBatchEmailService(emailList);
		}
		resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
		resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
		return resultJSON ; 
	}
}
